package com.zxp.mall.authserve.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zxp.mall.authserve.feign.MemberFeignService;
import com.zxp.mall.common.constant.AuthServerConstant;
import com.zxp.mall.common.vo.MemberRespVo;
import com.zxp.mall.authserve.vo.SocialUser;
import com.zxp.mall.common.utils.HttpUtils;
import com.zxp.mall.common.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//处理社交登录请求
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    //    http://gulimall.com/oauth2.0/gitee/success
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        System.out.println(code);
        Map<String, String> map = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
//        https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
//        https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}

        map.put("code", code);
        map.put("grant_type", "authorization_code");
        map.put("client_id", "d4320c1de19456f32136e9a3e4d3c3b1211bcd5fe94d4e6a4e81cae2b993efa9");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");

        map.put("client_secret", "4da401bc752df883213f41b24d66eebd477c853ea15d450223f498b3069a0231");
        HttpResponse response = null;
        response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, null, map);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
//                如果是第一次进来是自动注册(为当前的社交用户生成一个会员信息账号) 否则是登录
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                System.out.println(data);
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
